// pages/cart/cart.js
Page({
    data: {
      cartList: [],       // 购物车列表
      allSelected: false, // 是否全选
      totalPrice: 0,      // 总价格
      selectedCount: 0    // 选中数量
    },
  
    onShow() {
      this.loadCartData();
    },
  
    // 加载购物车数据
    loadCartData() {
      const cartList = wx.getStorageSync('cart') || [];
      this.setData({ cartList }, this.calculateTotal);
    },
  
    // 切换商品选中状态
    toggleSelect(e) {
      const index = e.currentTarget.dataset.index;
      const cartList = this.data.cartList;
      cartList[index].selected = !cartList[index].selected;
      this.setData({ cartList }, () => {
        this.calculateTotal();
        this.checkAllSelected();
      });
    },
  
    // 修改商品数量
    changeQuantity(e) {
      const { index, type } = e.currentTarget.dataset;
      const cartList = this.data.cartList;
      const item = cartList[index];
      
      if (type === 'minus' && item.quantity > 1) {
        item.quantity--;
      } else if (type === 'plus') {
        item.quantity++;
      }
      
      this.setData({ cartList }, () => {
        this.calculateTotal();
        this.saveCartData();
      });
    },
  
    // 删除商品
    deleteItem(e) {
      const index = e.currentTarget.dataset.index;
      wx.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            const cartList = this.data.cartList;
            cartList.splice(index, 1);
            this.setData({ cartList }, () => {
              this.calculateTotal();
              this.checkAllSelected();
              this.saveCartData();
            });
          }
        }
      });
    },
  
    // 全选/取消全选
    toggleAll() {
      const allSelected = !this.data.allSelected;
      const cartList = this.data.cartList.map(item => ({
        ...item,
        selected: allSelected
      }));
      
      this.setData({
        cartList,
        allSelected
      }, this.calculateTotal);
    },
  
    // 计算总价和选中数量
    calculateTotal() {
      let total = 0;
      let count = 0;
      
      this.data.cartList.forEach(item => {
        if (item.selected) {
          total += item.price * item.quantity;
          count += 1;
        }
      });
      
      this.setData({
        totalPrice: total.toFixed(2),
        selectedCount: count
      });
    },
  
    // 检查是否全选
    checkAllSelected() {
      const allSelected = this.data.cartList.every(item => item.selected);
      this.setData({ allSelected });
    },
  
    // 保存购物车数据
    saveCartData() {
      wx.setStorageSync('cart', this.data.cartList);
    },
  
    // 去结算
    goToSettlement() {
      if (this.data.selectedCount === 0) {
        wx.showToast({ title: '请选择商品', icon: 'none' });
        return;
      }
      wx.navigateTo({
        url: '/pages/order/confirm'
      });
    }
  });